package com.p7.architect.store.shoppingcart.application.converter;

import cn.hutool.core.collection.CollectionUtil;
import com.p7.architect.store.shoppingcart.application.command.dto.ShoppingCartDto;
import com.p7.architect.store.shoppingcart.application.command.dto.ShoppingItemDto;
import com.p7.architect.store.shoppingcart.domain.model.shoppingcart.ShoppingCart;
import com.p7.architect.store.shoppingcart.domain.model.shoppingcart.ShoppingItem;
import com.p7.architect.store.shoppingcart.infrastructure.repositoryimpl.vo.Sku;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ShoppingCartDtoConverter {

    public ShoppingCartDto converterToShoppingCartDto(ShoppingCart shoppingCart, List<Sku> skuList) {
        ShoppingCartDto dto = new ShoppingCartDto();
        dto.setShoppingCartId(shoppingCart.getShoppingCartId().getId());
        dto.setStoreId(shoppingCart.getStoreId().getId());
        dto.setUserId(shoppingCart.getUserId().getId());

        List<ShoppingItem> items = shoppingCart.getItems();
        Map<Long, Integer> skuIdMap = new HashMap<>();
        for (ShoppingItem item : items) {
            skuIdMap.put(item.getSkuId().getId(), item.getItemNum().getNum());
        }

        if (CollectionUtil.isEmpty(skuList)) {
            return dto;
        }

        List<ShoppingItemDto> shoppingItemDtoList = new ArrayList<>();
        int totalAmount = 0;
        for (Sku sku : skuList) {
            ShoppingItemDto itemDto = new ShoppingItemDto();
            itemDto.setNum(skuIdMap.get(sku.getSkuId()) == null ? 0 : skuIdMap.get(sku.getSkuId()));
            itemDto.setSkuId(sku.getSkuId());
            itemDto.setSkuTitle(sku.getSkuTitle());
            itemDto.setSkuDefaultImg(sku.getSkuDefaultImg());
            itemDto.setSpuId(sku.getSpuId());
            itemDto.setPrice(sku.getPrice());

            shoppingItemDtoList.add(itemDto);
            totalAmount = totalAmount + sku.getPrice() * itemDto.getNum();
        }
        dto.setShoppingItemDtoList(shoppingItemDtoList);
        dto.setTotalAmount(totalAmount);
        return dto;
    }
}
